package com.chungkui.check.expression.impl;

import com.chungkui.check.core.Constants;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.BaseMinMaxExpression;
import com.chungkui.check.handler.insidecheck.InsideType;
import com.chungkui.check.util.JsonUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author jason
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class JsonArrayExpression extends BaseMinMaxExpression {
    @Override
    public CheckResult match(Map<String, Object> params) {
        String val = MapUtils.getString(params, this.param);
        if (this.require != null && this.require && StringUtils.isBlank(val)) {
            String msg = MapUtils.getString(this.msg, Constants.NULL, normalMsg);
            return CheckResult.fail(this.code, this.param, msg, val);
        }
        if (StringUtils.isNotEmpty(val)) {
            List<Object> data = JsonUtil.jsonToObject(val, List.class);
            if (data == null) {
                return CheckResult.fail(this.code, this.param, MapUtils.getString(this.msg, Constants.FAIL, normalMsg), val);
            }
            int v = (data == null ? 0 : data.size());
            return super.checkMinMax(this.min, this.max, v);
        }
        return CheckResult.success();

    }

    @Override
    public void compile(Map<String, Object> config) {
        super.init(config);
        setIntegerMinMax(config);
    }

    @Override
    public InsideType getInsideType() {
        return InsideType.JSON_ARRAY;
    }


}
